// src/chat/chat.gateway.ts
import {
    WebSocketGateway,
    WebSocketServer,
    SubscribeMessage,
    MessageBody,
    ConnectedSocket,
  } from '@nestjs/websockets';
  import { Server, Socket } from 'socket.io';
  import { InjectModel } from '@nestjs/mongoose';
  import { Model, Types } from 'mongoose';
  import { ChatMessage } from './schemas/chat-message.schema';
  import { User, UserSchema , UserDocument} from "../users/schemas/user.schema"
  @WebSocketGateway({ cors: true })
  export class ChatGateway {
    @WebSocketServer()
    server: Server;
  
    private users: Map<string, string> = new Map(); // 用户 ID 和 Socket ID 的映射
  
    constructor(
      @InjectModel(ChatMessage.name) private chatMessageModel: Model<ChatMessage>,
      @InjectModel(User.name) private userModel: Model<User>, // 添加 User 模型
    ) {}
  
    handleConnection(client: Socket) {
      console.log(`Client connected: ${client.id}`);
    }
  
    handleDisconnect(client: Socket) {
      console.log(`Client disconnected: ${client.id}`);
      this.users.forEach((socketId, userId) => {
        if (socketId === client.id) {
          this.users.delete(userId);
        }
      });
    }
  
    @SubscribeMessage('join')
    handleJoin(@MessageBody() userId: string, @ConnectedSocket() client: Socket) {
      this.users.set(userId, client.id); // 将用户 ID 和 Socket ID 绑定
      console.log(`User ${userId} joined with socket ID ${client.id}`);
    }
  
    @SubscribeMessage('sendMessage')
    async handleMessage(
      @MessageBody() data: { senderId: string; receiverId: string; message: string },
    ) {
      const { senderId, receiverId, message } = data;
  
      // 保存消息到数据库
      const newMessage = new this.chatMessageModel({
        senderId,
        receiverId,
        message,
      });
      await newMessage.save();
  
      // 发送消息给接收者
      const receiverSocketId = this.users.get(receiverId);
      if (receiverSocketId) {
        this.server.to(receiverSocketId).emit('receiveMessage', {
          senderId,
          message,
        });

        // 发送消息提醒
        this.server.to(receiverSocketId).emit('messageNotification', {
          senderId,
          message: `您收到来自用户 ${senderId} 的新消息`,
        });

      // } else {
        console.log(`User ${receiverId} is not online.`);
      // }
    }
  }

// 新增：获取未读消息数量
    @SubscribeMessage('getUnreadCount')
    async handleGetUnreadCount(
      @MessageBody() userId: string,
      @ConnectedSocket() client: Socket,
    ) {
      // 查询所有未读消息，而不仅仅是计数
      const unreadMessages = await this.chatMessageModel.find({
        receiverId: userId,
        read: false,
      }).sort({ createdAt: -1 }); // 按时间倒序排列，最新的消息在前
      
      // 计算未读消息总数
      const unreadCount = unreadMessages.length;

     // 获取所有发送者的ID
      const senderIds = [...new Set(unreadMessages.map(msg => 
        typeof msg.senderId === 'object' && msg.senderId !== null ? msg.senderId!.toString() : (msg.senderId ?? '')
      ))];

      // 查询所有发送者的信息
      const senders = await this.userModel.find({
        _id: { $in: senderIds.map(user_id => new Types.ObjectId(user_id)) }
      });



      // 创建发送者ID到发送者信息的映射
      const senderMap = new Map();
      senders.forEach(sender => {
        senderMap.set(sender._id.toString(), {
          id: sender._id,
          username: sender.username,
          avatar: sender.avatar,
          // 添加其他需要的字段
        });
      });


      console.log('senders',senders);

      
      // 发送未读消息数量、发送者信息和消息内容给用户
      client.emit('unreadCountUpdate', { 
          count: unreadCount,
          messages: unreadMessages.map(msg => {
            const senderId = msg.senderId.toString();
            const sender = senderMap.get(senderId) || { id: senderId };
            return {
                messageId: msg._id,
                senderId: msg.senderId,
                message: msg.message,
                // createdAt: msg.createdAt ? new Date(msg.createdAt) : new Date(),
                sender: sender // 包含发送者的详细信息
            }
        })
      });
    }


      // 辅助方法：通过 Socket ID 获取用户 ID
  private getUserIdBySocketId(socketId: string): string | null {
    for (const [userId, id] of this.users.entries()) {
      if (id === socketId) {
        return userId;
      }
    }
    return null;
  }

    // 新增：标记消息为已读
  @SubscribeMessage('markAsRead')
  async handleMarkAsRead(
    @MessageBody() data: { messageId: string },
    @ConnectedSocket() client: Socket,
  ) {
    const { messageId } = data;
    
    // 更新消息状态为已读
    await this.chatMessageModel.findByIdAndUpdate(messageId, { read: true });
    
    // 可以在这里触发未读消息数量的更新
    const userId = this.getUserIdBySocketId(client.id);
    if (userId) {
      this.handleGetUnreadCount(userId, client);
    }
  }

  }